iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 19
0
Software Development

三十天利用Angular與.net Core開發實戰一波系列 第 19

Day 19 .NET Core 建立 Web API+ MongoDB 1/2

  • 分享至 

  • xImage
  •  

現在要來建立我們專案的後端資料庫與Web API了

MongoDB

首先建立簡單一個Test DB

db.Users.insert([
    {UserId:"1",UserName:"Linda"},
    {UserId:"2",UserName:"Lue"},
    {UserId:"3",UserName:"James",Birthday:"2000/01/01"},
    {UserId:"4",UserName:"Webber",Birthday:"1988/01/01"},
    {UserId:"5",UserName:"Wade",Birthday:"2010/01/01",Phone: "234-5678"}])

.NET Core Web API

接著開啟地表最強IDE- Visual Studio 2017

  • 我們先用vs2017新增一個WEB API專案

再來安裝連接MongoDB的driver

Models

  • 新建一個Models資料夾,並新增一個User.cs的類別,這邊BsonElement是跟MongoDB的Collection欄位一致
  • 記得要using MongoDB的相關Driver歐~
using MongoDB.Bson; 
using MongoDB.Bson.Serialization.Attributes;

namespace TestWebAPI.Models
{
    public class User
    {
        public ObjectId Id { get; set; }
        [BsonElement("UserId")]
        public string UserId { get; set; }
        [BsonElement("UserName")]
        public string UserName { get; set; }
        [BsonElement("Phone")]
        public string Phone { get; set; }
        [BsonElement("Birthday")]
        public string Birthday { get; set; }
    }
}

接著為了我們API回傳的方便

  • 新增一個Response.cs的類別,用途是處理api回傳時的統一格式。
public class Response<T>
    {
        public bool IsSuccess { get; set; }
        public T Data { get; set; }
        public string ErrorMessage { get; set; }
    }

  • 在Models中新增一個DataAccess.cs的類別,用途是連線MongoDB與Collection增刪修查
public class DataAccess
    {
        MongoClient _client;
        MongoServer _server;
        MongoDatabase _db;

        public DataAccess()
        {
            _client = new MongoClient("mongodb://localhost:27017");
            _server = _client.GetServer();
            _db = _server.GetDatabase("testDB");
        }

        public IEnumerable<User> GetUsers()
        {
            return _db.GetCollection<User>("Users").FindAll();
        }


        public User GetUser(ObjectId id)
        {
            var res = Query<User>.EQ(p => p.Id, id);
            return _db.GetCollection<User>("Users").FindOne(res);
        }

        public User CreateUser(User user)
        {
            _db.GetCollection<User>("Users").Save(user);
            return user;
        }

        public bool UpdateUser(ObjectId id, User user)
        {
            user.Id = id;
            var res = Query<User>.EQ(u => u.Id, id);
            var operation = Update<User>.Replace(user);
            var result = _db.GetCollection<User>("Users").Update(res, operation);
            return !result.HasLastErrorMessage;
        }
        public bool RemoveUser(ObjectId id)
        {
            var res = Query<User>.EQ(e => e.Id, id);
            var operation = _db.GetCollection<User>("Users").Remove(res);
            return !operation.HasLastErrorMessage;
        }
    }
}

我們習慣透過Repository來在Controller與Database中溝通

Handler-Repository

  • 新增IUserRepository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestWebAPI.Models;

namespace TestWebAPI.Handler
{
    public interface IUserRepository
    {
        Response<User> AddUser(User u);
        Response<IEnumerable<User>> GetAllUser();
        Response<bool> DeleteUser(string Id);
        Response<User> GetUserById(string Id);
        Response<bool> UpdateUser(string Id, User u);
    }
}
  • 新增UserRepository,記得繼承IUserRepository
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestWebAPI.Models;

namespace TestWebAPI.Handler
{
    public class UserRepository : IUserRepository
    {
        private readonly DataAccess _db;
        public UserRepository(DataAccess db)
        {
            _db = db;
        }

        public Response<User> AddUser(User u)
        {
            var result = new Response<User>();
            result.IsSuccess = true;
            try
            {
                result.Data = _db.CreateUser(u);
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
            }
            return result;
        }

        public Response<bool> DeleteUser(string Id)
        {
            var result = new Response<bool>();
            result.IsSuccess = true;
            try
            {
                var objId = new ObjectId(Id);
                result.Data = _db.RemoveUser(objId);
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        public Response<IEnumerable<User>> GetAllUser()
        {
            var result = new Response<IEnumerable<User>>();
            result.IsSuccess = true;
            try
            {
                result.Data = _db.GetUsers();
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        public Response<User> GetUserById(string Id)
        {
            var result = new Response<User>();
            result.IsSuccess = true;
            try
            {
                var objId = new ObjectId(Id);
                result.Data = _db.GetUser(objId);
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
            }
            return result;
        }

        public Response<bool> UpdateUser(string Id, User u)
        {
            var result = new Response<bool>();
            result.IsSuccess = true;
            try
            {
                var objId = new ObjectId(Id);
                result.Data = _db.UpdateUser(objId, u);
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
            }
            return result;
        }
    }
}

Controllers

前面建置完成後,最後可以寫Web API了

  • 新建一個Controllers資料夾,新增UserAPIController.cs的類別
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using TestWebAPI.Handler;
using TestWebAPI.Models;

namespace TestWebAPI.Controllers
{
    [Route("api/user/[action]/")]
    public class UserAPIController : Controller
    {
        private readonly IUserRepository _userRepository;

        public UserAPIController(IUserRepository repository)
        {
            _userRepository = repository;
        }

        // GET: api/<controller>
        [HttpGet]
        public Response<IEnumerable<User>> GetAllUser()
        {
            return _userRepository.GetAllUser();
        }

        // GET api/<controller>/5
        [HttpGet]
        public Response<User> GetUserById(string Id)
        {
            var response = _userRepository.GetUserById(Id);
            var s = response.Data.Id.ToString();
            return response;
        }

        // POST api/<controller>
        [HttpPost]
        public Response<User> AddUser([FromBody]User u)
        {
            var response = _userRepository.AddUser(u);
            return response;
        }

        [HttpPut]
        public Response<bool> UpdateUser(string Id, [FromBody] User u)
        {
            var response = _userRepository.UpdateUser(Id, u);
            return response;
        }

        // DELETE api/<controller>/5
        [HttpDelete]
        public Response<bool> DeleteUser(string Id)
        {
            var response = _userRepository.DeleteUser(Id);
            return response;
        }
    }
}

前置作業大致到這

To be continued


上一篇
Day 18 AngularTri 專案架構配置-主控版面
下一篇
Day 20 .NET Core 建立 Web API+ MongoDB 2/2
系列文
三十天利用Angular與.net Core開發實戰一波32
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言